/**
 * @filename:SysMenuServiceImpl 2022年1月27日
 * @project Wonder wallet Framework  V1.0
 * Copyright(c) 2018 LuZhongren Co. Ltd. 
 * All right reserved. 
 */
package com.wonder.admin.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wonder.admin.domain.SysMenu;
import com.wonder.admin.domain.SysRole;
import com.wonder.admin.domain.vo.SysMenuVo;
import com.wonder.admin.mapper.SysMenuDao;
import com.wonder.admin.request.SysMenuRequest;
import com.wonder.admin.service.SysMenuService;
import com.wonder.common.utils.StringUtils;
import com.wonder.common.utils.bean.BeanUtils;


/**   
 * @Description:TODO(菜单管理服务实现)
 *
 * @version: V1.0
 * @author: LuZhongren
 * 
 */
@Service
public class SysMenuServiceImpl  extends ServiceImpl<SysMenuDao, SysMenu> implements SysMenuService  {

   /**
     * 修改菜单管理信息
     * 
     * @param SysMenu信息
     * @return 结果
     */
    @Override
    public int updateEx(SysMenu sysMenu){
       if(sysMenu!=null)
		     return this.baseMapper.updateById(sysMenu);
       return 0;
    }
    
    
    /**
	 * Description:菜单管理分页返回
	 * @request:检索条件
	 * @page：分页参数
	 * @return:分页记录
	 */
	@Override 
	public IPage<SysMenu> selectList(SysMenuRequest request, Page<SysMenu> page){
	    LambdaQueryWrapper<SysMenu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
	               
	    if (null != request.getPid()) {
	       lambdaQueryWrapper.eq(SysMenu::getPid, request.getPid());
	      }               
        
	    if (null != request.getApp_id()) {
	       lambdaQueryWrapper.eq(SysMenu::getApp_id, request.getApp_id());
	      }               
	    
		lambdaQueryWrapper.orderByAsc(SysMenu::getSortid);	
		Page<SysMenu> selectPage = this.baseMapper.selectPage(page, lambdaQueryWrapper);

		return selectPage;
    }
	
	
	
	  /**
     * 构建前端所需要树结构
     * 
     * @param menus 菜单列表
     * @return 树结构列表
     */
	@Override
	public List<SysMenu> buildMenuTree(List<SysMenu> menus) {
		// TODO Auto-generated method stub
		List<SysMenu> returnList = new ArrayList<SysMenu>();
        for (Iterator<SysMenu> iterator = menus.iterator(); iterator.hasNext();)
        {
            SysMenu t = (SysMenu) iterator.next();
            // 根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getPid() == 0)
            {
                recursionFn(menus, t);
                returnList.add(t);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = menus;
        }
        return returnList;
	}
	
	
	 /**
     * 构建前端用户显示所需要全部菜单树结构
     * 
     * @param menus 菜单列表
     * @return 树结构列表
     */
	@Override
	public List<SysMenuVo> buildBaseMenuTree(List<SysMenuVo> menus) {
		// TODO Auto-generated method stub
		List<SysMenuVo> returnList = new ArrayList<SysMenuVo>();
        for (Iterator<SysMenuVo> iterator = menus.iterator(); iterator.hasNext();)
        {
        	SysMenuVo t = (SysMenuVo) iterator.next();
            // 根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getPid() == 0)
            {
                recursionFnVo(menus, t);
                returnList.add(t);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = menus;
        }
        return returnList;
	}
	
	/**
	 * 遍历获取 COMPONENT 路径
	 * 
	 * @param baseMenus
	 * @return
	 */

	@Override
	public List<Map<String,Object>> getComponents(List<SysMenuVo> baseMenus) {
		List<Map<String, Object>> components = new ArrayList<>();
		
		for(SysMenuVo item: baseMenus){
			Map<String, Object> mapItem = new HashMap<>();
			mapItem.put("name",item.getName());
			mapItem.put("path", item.getPath());
			Map<String,Object> metaMap=new HashMap<String, Object>();
			metaMap.put("title", item.getTitle());
			mapItem.put("meta",metaMap );
			mapItem.put("component_path", item.getComponent_path());
			components.add(mapItem);
			
			if(item.getChildren() !=null) {
				components.addAll(getComponents(item.getChildren()));
				
			}

		}
		return components;

	}
	
	
	/**
	 * 获取隐藏的非菜单路由
	 * @param role
	 * @return
	 */
	@Override
	public List<Map<String,Object>> getHiddenComponents(SysRole role){
		List<Map<String,Object>> components=new ArrayList<Map<String,Object>>();
		
		List<SysMenu> list=this.list(new QueryWrapper<SysMenu>().eq("status", 0).eq("app_id", 1).ne("component_path", "").orderByAsc("sortid"));
		List<String> rightList= Arrays.asList(StringUtils.split(role.getAccess_table(),","));
		for(SysMenu item:list) {
			if(role.getRole_id()==1 || rightList.contains(item.getController_name())) {
				Map<String, Object> mapItem = new HashMap<>();
				mapItem.put("name",item.getController_name());
				mapItem.put("path", "/"+item.getModule()+"/"+item.getController_name().replace('/', '.')+"/index.html");
				Map<String,Object> metaMap=new HashMap<String, Object>();
				metaMap.put("title", item.getTitle());
				mapItem.put("meta",metaMap );
				mapItem.put("component_path", item.getComponent_path());
				components.add(mapItem);
			}
		}
		
		return components;
	}
	
	
	@Override
	public  List<SysMenuVo> getBaseMenus(SysRole role) {
		List<SysMenu> list=this.list(new QueryWrapper<SysMenu>().eq("status", 1).eq("app_id", 1).orderByAsc("sortid"));
		List<SysMenuVo> listVos=new ArrayList<SysMenuVo>();
//		
		for(SysMenu item:list) {
			SysMenuVo itemVo=new SysMenuVo();
			BeanUtils.copyProperties(item, itemVo);
			
			itemVo.setPath("/"+item.getModule()+"/"+item.getController_name().replace('/', '.')+"/index.html");
			itemVo.setName(item.getController_name());
			if(item.getIcon()==null)itemVo.setIcon("el-icon-menu");
			listVos.add(itemVo);
			

		}
		//Not belong to super role
		if(role.getRole_id() !=1) {
			List<String> rightList= Arrays.asList(StringUtils.split(role.getAccess_table(),","));
			List<SysMenuVo> tempVos=new ArrayList<SysMenuVo>();
					
			for(SysMenuVo item:listVos) {
				if(!rightList.contains(item.getName()))
					tempVos.add(item);
					//listVos.remove(item);
			}
			listVos.removeAll(tempVos);
			
		}
	
		return buildBaseMenuTree(listVos);
	}
	
	/**
     * 递归列表
	 * @param <T>
     * 
     * @param list
     * @param t
     */

    private void recursionFn(List<SysMenu> list, SysMenu t)
    {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenu tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                // 判断是否有子节点
                Iterator<SysMenu> it = childList.iterator();
                while (it.hasNext())
                {
                    SysMenu n = (SysMenu) it.next();
                    recursionFn(list, n);
                }
            }
        }
    }
    
    private void recursionFnVo(List<SysMenuVo> list, SysMenuVo t)
    {
        // 得到子节点列表
        List<SysMenuVo> childList = getChildListVo(list, t);
        t.setChildren(childList);
        for (SysMenuVo tChild : childList)
        {
            if (hasChildVo(list, tChild))
            {
                // 判断是否有子节点
                Iterator<SysMenuVo> it = childList.iterator();
                while (it.hasNext())
                {
                	SysMenuVo n = (SysMenuVo) it.next();
                    recursionFnVo(list, n);
                }
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t)
    {
        List<SysMenu> tlist = new ArrayList<SysMenu>();
        Iterator<SysMenu> it = list.iterator();
        while (it.hasNext())
        {
            SysMenu n = (SysMenu) it.next();
            if (n.getPid().longValue() == t.getMenu_id())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }
    
    
    /**
     * 得到子节点列表
     */
    private List<SysMenuVo> getChildListVo(List<SysMenuVo> list, SysMenuVo t)
    {
        List<SysMenuVo> tlist = new ArrayList<SysMenuVo>();
        Iterator<SysMenuVo> it = list.iterator();
        while (it.hasNext())
        {
        	SysMenuVo n = (SysMenuVo) it.next();
            if (n.getPid().longValue() == t.getMenu_id())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenu> list, SysMenu t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
    
    /**
     * 判断是否有子节点
     */
    private boolean hasChildVo(List<SysMenuVo> list, SysMenuVo t)
    {
        return getChildListVo(list, t).size() > 0 ? true : false;
    }
    
    

  
	
}